import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Space,
  Button,
  Tag,
  Modal,
  message,
  Input,
  Select,
  DatePicker,
  Typography,
} from "antd";
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  MessageOutlined,
  LikeOutlined,
  EyeOutlined,
} from "@ant-design/icons";
import type { DiscussionPost } from "../../../types/discussion";
import { useUser } from "../../../contexts/UserContext";
import PermissionGuard from "../../../components/PermissionGuard";

const { Title } = Typography;
const { Search } = Input;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

interface DiscussionFilter {
  keyword?: string;
  sortBy: "latest" | "popular" | "mostReplies";
  timeRange?: [string, string];
}

const DiscussionManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [selectedRows, setSelectedRows] = useState<string[]>([]);

  useEffect(() => {
    loadDiscussions();
  }, [filter]);

  const loadDiscussions = async () => {
    setLoading(true);
    try {
      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 300)); // 模拟加载延迟
      
      // 生成56条讨论数据
      const studentNames = [
        "李明轩", "王雨涵", "张浩然", "刘雅琪", "陈思远", "杨梦瑶", "赵天宇", "孙诗涵", "周博文", "吴欣怡",
        "徐子轩", "朱雨桐", "胡志强", "郭雅婷", "何俊杰", "马晓雯", "韩志豪", "郑雅文", "冯浩然", "曹梦琪",
        "彭志强", "董雅涵", "袁博文", "潘雨桐", "田志豪", "姜雅文", "魏浩然", "蒋梦琪", "韦志强", "傅雅涵",
        "沈博文", "卢雨桐", "姚志豪", "钱雅文", "汪浩然", "田梦琪", "任志强", "武雅涵", "戴博文", "贾雨桐",
        "夏志豪", "钟雅文", "邱浩然", "骆梦琪", "高志强", "蔡雅涵", "樊博文", "胡雨桐", "凌志豪", "霍雅文",
        "虞浩然", "万梦琪", "支志强", "柯雅涵", "昝博文", "管雨桐"
      ];

      const teacherNames = [
        "王峰华", "李志强", "张明远", "刘建国", "陈志伟", "杨建华", "赵德明", "黄志强", "周建军", "吴国强",
        "徐志强", "孙建华", "马志强", "朱建国", "胡志强", "郭建华", "何志强", "高建国", "林志强", "罗建华"
      ];

      const courseNames = [
        "操作系统原理", "数据结构与算法", "计算机网络", "数据库原理", "软件工程", "机器学习", "人工智能导论",
        "计算机组成原理", "编译原理", "软件测试", "Web开发技术", "移动应用开发", "云计算技术", "大数据处理",
        "网络安全基础", "数字图像处理", "自然语言处理", "计算机图形学", "嵌入式系统", "物联网技术"
      ];

      const discussionTitles = [
        "关于操作系统课程的学习建议", "数据结构算法题求解", "软件工程项目的团队协作经验分享", "机器学习入门指南",
        "网络安全实践项目讨论", "数据库设计最佳实践", "Web开发框架选择建议", "移动应用性能优化技巧",
        "云计算部署方案讨论", "大数据分析项目经验", "人工智能应用案例分享", "计算机图形学实验心得",
        "嵌入式系统开发挑战", "物联网设备连接问题", "软件测试自动化实践", "编译原理学习难点",
        "计算机网络协议分析", "数字图像处理算法实现", "自然语言处理技术应用", "计算机组成原理实验指导",
        "深度学习模型训练技巧", "软件架构设计原则", "前端开发技术栈选择", "后端服务性能优化",
        "移动端用户体验设计", "云原生应用开发", "数据挖掘算法应用", "机器学习模型部署",
        "人工智能伦理问题讨论", "计算机视觉技术发展", "区块链技术在教育中的应用", "虚拟现实技术体验",
        "增强现实应用开发", "边缘计算技术探讨", "5G技术对教育的影响", "量子计算基础知识",
        "生物信息学算法", "密码学基础理论", "软件安全开发实践", "DevOps最佳实践",
        "微服务架构设计", "容器化技术应用", "服务网格技术", "API设计规范",
        "数据库性能优化", "缓存策略设计", "消息队列应用", "分布式系统设计",
        "高并发系统架构", "系统监控与告警", "日志分析与处理", "自动化测试实践",
        "持续集成与部署", "代码质量保证", "技术文档编写", "开源项目贡献指南"
      ];

      const tags = [
        ["学习方法", "课程建议"], ["算法", "二叉树"], ["项目经验", "团队协作"], ["入门指南", "学习资源"],
        ["实践项目", "网络安全"], ["数据库设计", "最佳实践"], ["Web开发", "框架选择"], ["性能优化", "移动应用"],
        ["云计算", "部署方案"], ["大数据", "数据分析"], ["人工智能", "应用案例"], ["计算机图形学", "实验心得"],
        ["嵌入式系统", "开发挑战"], ["物联网", "设备连接"], ["软件测试", "自动化"], ["编译原理", "学习难点"],
        ["计算机网络", "协议分析"], ["数字图像处理", "算法实现"], ["自然语言处理", "技术应用"], ["计算机组成", "实验指导"],
        ["深度学习", "模型训练"], ["软件架构", "设计原则"], ["前端开发", "技术栈"], ["后端服务", "性能优化"],
        ["移动端", "用户体验"], ["云原生", "应用开发"], ["数据挖掘", "算法应用"], ["机器学习", "模型部署"],
        ["人工智能", "伦理问题"], ["计算机视觉", "技术发展"], ["区块链", "教育应用"], ["虚拟现实", "技术体验"],
        ["增强现实", "应用开发"], ["边缘计算", "技术探讨"], ["5G技术", "教育影响"], ["量子计算", "基础知识"],
        ["生物信息学", "算法"], ["密码学", "基础理论"], ["软件安全", "开发实践"], ["DevOps", "最佳实践"],
        ["微服务", "架构设计"], ["容器化", "技术应用"], ["服务网格", "技术"], ["API设计", "规范"],
        ["数据库", "性能优化"], ["缓存策略", "设计"], ["消息队列", "应用"], ["分布式系统", "设计"],
        ["高并发", "系统架构"], ["系统监控", "告警"], ["日志分析", "处理"], ["自动化测试", "实践"],
        ["持续集成", "部署"], ["代码质量", "保证"], ["技术文档", "编写"], ["开源项目", "贡献指南"]
      ];

      const mockDiscussions: DiscussionPost[] = Array.from({ length: 56 }, (_, index) => {
        const studentIndex = index % studentNames.length;
        const teacherIndex = index % teacherNames.length;
        const courseIndex = index % courseNames.length;
        const titleIndex = index % discussionTitles.length;
        const tagIndex = index % tags.length;
        
        const hasReplies = index % 3 === 0; // 每3个讨论有1个回复
        const hasAIResponse = index % 2 === 0; // 每2个讨论有1个AI回复
        
        return {
          id: `d${index + 1}`,
          title: discussionTitles[titleIndex],
          content: `这是第${index + 1}个讨论的内容，关于${courseNames[courseIndex]}课程的学习讨论...`,
          author: {
            id: `s${studentIndex + 1}`,
            name: studentNames[studentIndex],
            role: "student",
          },
          course: {
            id: `c${courseIndex + 1}`,
            name: courseNames[courseIndex],
          },
          tags: tags[tagIndex],
          views: Math.floor(Math.random() * 500) + 50,
          likes: Math.floor(Math.random() * 100) + 5,
          replies: hasReplies ? [
            {
              id: `r${index + 1}`,
              content: `这是第${index + 1}个讨论的回复内容，提供了很好的建议和指导...`,
              author: {
                id: `t${teacherIndex + 1}`,
                name: teacherNames[teacherIndex],
                role: "teacher",
              },
              createTime: `2024-01-${String(20 - Math.floor(index / 3)).padStart(2, '0')} ${String(10 + index % 10).padStart(2, '0')}:${String(30 + index % 30).padStart(2, '0')}:00`,
              likes: Math.floor(Math.random() * 20) + 1,
            },
          ] : [],
          createTime: `2024-01-${String(20 - Math.floor(index / 2)).padStart(2, '0')} ${String(14 + index % 6).padStart(2, '0')}:${String(20 + index % 40).padStart(2, '0')}:00`,
          aiResponse: hasAIResponse,
        };
      });

      // 根据过滤条件处理数据
      let filteredDiscussions = mockDiscussions;

      // 关键词搜索
      if (filter.keyword) {
        const keyword = filter.keyword.toLowerCase();
        filteredDiscussions = filteredDiscussions.filter(
          discussion =>
            discussion.title.toLowerCase().includes(keyword) ||
            discussion.content.toLowerCase().includes(keyword) ||
            discussion.author.name.toLowerCase().includes(keyword)
        );
      }

      // 排序
      switch (filter.sortBy) {
        case "latest":
          filteredDiscussions.sort((a, b) => 
            new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
          );
          break;
        case "popular":
          filteredDiscussions.sort((a, b) => b.views - a.views);
          break;
        case "mostReplies":
          filteredDiscussions.sort((a, b) => (b.replies?.length || 0) - (a.replies?.length || 0));
          break;
      }

      // 时间范围过滤
      if (filter.timeRange) {
        const [startDate, endDate] = filter.timeRange;
        filteredDiscussions = filteredDiscussions.filter(discussion => {
          const discussionDate = new Date(discussion.createTime);
          return discussionDate >= new Date(startDate) && discussionDate <= new Date(endDate);
        });
      }

      setDiscussions(filteredDiscussions);
      setLoading(false);
    } catch (error) {
      message.error("加载讨论列表失败");
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter({ ...filter, keyword: value });
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter({ ...filter, sortBy: value });
  };

  const handleDateRangeChange = (dates: any) => {
    if (dates) {
      setFilter({
        ...filter,
        timeRange: dates.map((date: any) => date.format("YYYY-MM-DD")),
      });
    } else {
      setFilter({ ...filter, timeRange: undefined });
    }
  };

  const handleDelete = (ids: string[]) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${ids.length} 条讨论吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          // 模拟删除成功
          await new Promise((resolve) => setTimeout(resolve, 200));
          message.success("删除成功");
          loadDiscussions();
          setSelectedRows([]);
        } catch (error) {
          message.error("删除失败，请重试");
        }
      },
    });
  };

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (text: string, record: DiscussionPost) => (
        <Space>
          <a href={`/discussion/${record.id}`}>{text}</a>
          {record.aiResponse && <Tag color="purple">AI已回复</Tag>}
        </Space>
      ),
    },
    {
      title: "作者",
      dataIndex: ["author", "name"],
      key: "author",
      render: (text: string, record: DiscussionPost) => (
        <Space>
          <UserOutlined />
          {text}
          <Tag color={record.author.role === "teacher" ? "blue" : undefined}>
            {record.author.role === "teacher" ? "教师" : "学生"}
          </Tag>
        </Space>
      ),
    },
    {
      title: "课程",
      dataIndex: ["course", "name"],
      key: "course",
    },
    {
      title: "标签",
      dataIndex: "tags",
      key: "tags",
      render: (tags: string[]) => (
        <Space>{tags?.map((tag) => <Tag key={tag}>{tag}</Tag>)}</Space>
      ),
    },
    {
      title: "统计",
      key: "stats",
      render: (_: any, record: DiscussionPost) => (
        <Space>
          <span>
            <EyeOutlined /> {record.views}
          </span>
          <span>
            <LikeOutlined /> {record.likes}
          </span>
          <span>
            <MessageOutlined /> {record.replies?.length || 0}
          </span>
        </Space>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "createTime",
      key: "createTime",
      sorter: (a: DiscussionPost, b: DiscussionPost) =>
        new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: DiscussionPost) => (
        <Space>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete([record.id])}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="discussion.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Title level={4} style={{ margin: 0 }}>
                讨论管理
              </Title>
            </Space>

            <Space style={{ marginBottom: 16 }}>
              <Search
                placeholder="搜索讨论..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
              <Select
                value={filter.sortBy}
                onChange={handleSortChange}
                style={{ width: 120 }}
                options={[
                  { label: "最新", value: "latest" },
                  { label: "最热", value: "popular" },
                  { label: "最多回复", value: "mostReplies" },
                ]}
              />
              <RangePicker onChange={handleDateRangeChange} />
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                disabled={selectedRows.length === 0}
                onClick={() => handleDelete(selectedRows)}
              >
                批量删除
              </Button>
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={discussions}
              loading={loading}
              rowSelection={{
                selectedRowKeys: selectedRows,
                onChange: (selectedRowKeys) =>
                  setSelectedRows(selectedRowKeys as string[]),
              }}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条讨论`,
              }}
            />
          </Space>
        </Card>
      </div>
    </PermissionGuard>
  );
};

export default DiscussionManagement;
